package com.nsxy.manager.common.utils;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.nsxy.manager.user.beans.Account;
import com.nsxy.manager.user.service.IAccountService;

/**
 * 设置登录信息、权限信息
 * @author 潜行的青衣
 * @see
 */
public class ShiroRealm extends AuthorizingRealm {
	
	@Resource
	private IAccountService accountService;
	
	public ShiroRealm(CacheManager cacheManager) {
        super(cacheManager);
    }
	
	public ShiroRealm(CredentialsMatcher matcher) {
        super(matcher);
    }
	
	public ShiroRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
		super(cacheManager, matcher);
	}
	
	/**
	 * 登录
	 */
	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		Account account = this.accountService.findByAccount((String) token.getPrincipal());
		if(account == null) {
			throw new UnknownAccountException("no such account");
		}
		return new SimpleAccount(account, account.getPassword(), this.getName());
	}

	/**
	 * 复权
	 */
	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermission("user:manage:browse");
		return info;
	}

}
